package com.fessc.develop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fessc.develop.entity.dbvo.TBatchRunJob;
import com.fessc.develop.mapper.TBatchRunJobMapper;
import com.fessc.develop.model.enums.EnumJobStatus;
import com.fessc.develop.service.interfaces.ITBatchRunJobService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author y
 * @since 2024-07-08
 */
@Slf4j
@Service
public class TBatchRunJobServiceImpl extends ServiceImpl<TBatchRunJobMapper, TBatchRunJob> implements ITBatchRunJobService {

    /**
     * 定时任务启动加载
     */
    @PostConstruct
    void init() {
        //更改定时任务执行状态，防止由于重启时，由于强制停止正在执行的任务，导致状态一直是“运行中”，从而影响正常执行
        List<TBatchRunJob> batchRunJobList = this.list(new QueryWrapper<TBatchRunJob>());
        batchRunJobList.forEach(tBatchRunJob -> {
            log.info("==============加载定时任务状态==============" + tBatchRunJob.getTaskCode());
            tBatchRunJob.setStatus(EnumJobStatus.SUCCESS.toString());
            updateJobByTaskCode(tBatchRunJob);
        });
    }

    /**
     * 根据定时任务编号，查询定时任务记录
     *
     * @param taskCode 定时任务编号
     * @return 定时任务记录
     */
    @Override
    public TBatchRunJob getJobByTaskCode(String taskCode) {
        return this.getOne(new QueryWrapper<TBatchRunJob>().eq("TASK_CODE", taskCode));
    }

    /**
     * 更新定时任务
     *
     * @param batchRunJob 定时任务
     * @return 更新成功失败标志
     */
    @Override
    public Boolean updateJobByTaskCode(TBatchRunJob batchRunJob) {
        UpdateWrapper<TBatchRunJob> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("LAST_RUN_DATE", batchRunJob.getLastRunDate())
                .set("LAST_RUN_START", batchRunJob.getLastRunStart())
                .set("LAST_RUN_END", batchRunJob.getLastRunEnd())
                .set("STATUS", batchRunJob.getStatus())
                .eq("TASK_CODE", batchRunJob.getTaskCode());
        return this.update(updateWrapper);
    }
}
